package com.fang.algorithm.zuo.linked;

/**
 * @author fanglingxiao
 * @version 1.0
 * @description 双链表反转
 * @date 2022/4/23 12:28 上午
 **/
public class Test02_ReverseDoubleLinkedList {

    public static class DoubleNode {
        private int value;
        private DoubleNode next;
        private DoubleNode last;

        public DoubleNode(int value) {
            this.value = value;
        }
    }

    public static void main(String[] args) {
        DoubleNode node1 = new DoubleNode(1);
        DoubleNode node2 = new DoubleNode(2);
        DoubleNode node3 = new DoubleNode(3);
        node1.next = node2;
        node2.next = node3;
        node3.last = node2;
        node2.last = node1;

//        DoubleNode reverseNode = reverseDoubleLinkedList(node1);
        DoubleNode reverseNode = reverseDoubleLinkedList2(node1);
    }

    private static DoubleNode reverseDoubleLinkedList2(DoubleNode head) {
        DoubleNode pre = null;
        DoubleNode next;
        while (head != null) {
            next = head.next;
            head.last = next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }

    public static DoubleNode reverseDoubleLinkedList(DoubleNode head) {
        DoubleNode pre = null;
        DoubleNode next = null;
        while (head != null) {
            next = head.next;
            head.next = pre;
            head.last = next;
            pre = head;
            head = next;
        }
        return pre;
    }
}
